package com.gigi.searchcenterbackendmaster.manager;

import cn.hutool.core.util.StrUtil;
import com.gigi.searchcenterbackendmaster.datasource.*;
import com.gigi.searchcenterbackendmaster.model.enums.ErrorCodeEnum;
import com.gigi.searchcenterbackendmaster.model.enums.SearchTypeEnum;
import com.gigi.searchcenterbackendmaster.model.request.SearchRequest;
import com.gigi.searchcenterbackendmaster.model.vo.SearchVO;
import com.gigi.searchcenterbackendmaster.util.ThrowUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 搜索门面
 *
 * @author Gigi
 * @date 2024/8/17 16:52
 */
@Component
public class SearchFacade {

    @Resource
    private ArticleDataSource articleDataSource;

    @Resource
    private PictureDataSource pictureDataSource;

    @Resource
    private UserDataSource userDataSource;

    @Resource
    private DataSourceRegistry dataSourceRegistry;

    /**
     * 聚合搜索
     *
     * @param request
     * @return
     */
    public SearchVO searchAll(SearchRequest request) {
        SearchVO searchVO = new SearchVO();

        // 不传类型搜索所有
        if (StrUtil.isBlank(request.getType())) {
            searchVO.setArticleList(articleDataSource.doSearch(request.getKeyword()));
            searchVO.setPictureList(pictureDataSource.doSearch(request.getKeyword()));
            searchVO.setUserList(userDataSource.doSearch(request.getKeyword()));

        } else {
            // 否则根据类型搜索

            // 1、类型合法校验
            SearchTypeEnum typeEnum = SearchTypeEnum.getEnumByValue(request.getType());
            ThrowUtil.throwIf(Objects.isNull(typeEnum), ErrorCodeEnum.PARAMS_ERROR, "搜索类型错误");

            // 2、根据类型获取数据源
            DataSource<T> dataSource = dataSourceRegistry.getDataSourceByType(request.getType());
            ThrowUtil.throwIf(Objects.isNull(dataSource), ErrorCodeEnum.SYSTEM_ERROR, "数据源不存在");

            // 3、执行搜索
            searchVO.setDataList(dataSource.doSearch(request.getKeyword()));
        }

        return searchVO;
    }

}
